package com.yxhl.zoume.utils.permission;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;

import com.yxhl.zoume.domain.interactor.ZMEventSubscriber;
import com.yxhl.zoume.utils.LOG;
import com.yxhl.zoume.utils.ZMDialog;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by demo001 on 16/04/05.
 * 权限工具类,对PermissionHelper辅助类提供方法支持
 */
class PermissionUtils {

    private static final String TAG = PermissionUtils.class.getSimpleName();

    private static final int REQUEST_CODE_DEFAULT = 11;


    /**
     * 检查多个危险权限是否授权
     *
     * @param context
     * @param permissions
     * @return
     */
    public static boolean checkGroupPermissions(Context context, String[] permissions) {
        int[] results = null;
        if (context != null && permissions != null) {
            int length = permissions.length;
            if (length > 0) {
                results = new int[length];
                for (int i = 0; i < length; i++) {
                    int selfPermission = ContextCompat.checkSelfPermission(context, permissions[i]);
                    if (selfPermission == PackageManager.PERMISSION_GRANTED) {
                        results[i] = 0;
                    } else {
                        results[i] = -1;
                    }
                }
            }
        }
        int sum = 0;
        if (results != null) {
            for (int a : results) {
                sum += a;
            }
        }

        return (sum >= 0);
    }

    /**
     * 开启多个危险权限请求
     *
     * @param activity
     * @param permissions
     * @param alertDialogMessages
     */
    protected static void takeGroupPermissions(final Activity activity, final String[] permissions, String[] alertDialogMessages) {
        if (activity != null && permissions != null && alertDialogMessages != null) {
            int permissionLength = permissions.length;
            int alertMessageLength = alertDialogMessages.length;
            if (permissionLength > 0 && alertMessageLength > 0) {
                List<String> requestPermissions = new ArrayList<>();

                if (permissionLength == alertMessageLength) {
                    int[] permissionFlags = new int[permissionLength];

                    for (int i = 0; i < permissionLength; i++) {
                        final int index = i;
                        permissionFlags[index] = ContextCompat.checkSelfPermission(activity, permissions[index]);

                        if (PackageManager.PERMISSION_DENIED == permissionFlags[index]) {
                            //之前拒绝过,则需要解释
                            if (ActivityCompat.shouldShowRequestPermissionRationale(activity, permissions[index])) {
                                LOG.e("permission", "explain why we need to open the permission");

                                ZMDialog zmDialog = new ZMDialog.Builder(activity)
                                        .setMessage(alertDialogMessages[index])
                                        .setPositiveMessage("开启")
                                        .setPositiveClickEvent(new ZMEventSubscriber() {
                                            @Override
                                            public void onNext(Object o) {
                                                super.onNext(o);
                                                requestOnePermission(activity, permissions[index]);
                                            }
                                        }).show();

                            } else {
                                requestPermissions.add(permissions[index]);
                            }
                        }
                    }

                    int size = requestPermissions.size();
                    if (size > 0) {
                        requestGroupPermission(activity, requestPermissions);
                    }

                } else {
                    throw new IllegalArgumentException("the length of Permission Array need to equal of AlertMessage Array's  ");
                }
            } else {
                throw new IllegalArgumentException("Permission Array and AlertMessage Array couldn't be empty");
            }
        }
    }

    /**
     * 开启多个危险权限请求
     *
     * @param activity
     * @param permissions
     * @param alertDialogMessages
     * @param requestCode
     */
    protected static void takeGroupPermissions(final Activity activity, final String[] permissions,
                                               String[] alertDialogMessages, final int requestCode) {
        if (activity != null && permissions != null && alertDialogMessages != null) {
            int permissionLength = permissions.length;
            int alertMessageLength = alertDialogMessages.length;
            if (permissionLength > 0 && alertMessageLength > 0) {

                //存放需要授权的危险权限
                List<String> requestPermissionList = new ArrayList<>();

                if (permissionLength == alertMessageLength) {
                    int[] permissionFlags = new int[permissionLength];

                    for (int i = 0; i < permissionLength; i++) {
                        final int index = i;
                        permissionFlags[index] = ContextCompat.checkSelfPermission(activity, permissions[index]);

                        if (PackageManager.PERMISSION_DENIED == permissionFlags[index]) {
                            //之前拒绝过,则需要解释
                            if (ActivityCompat.shouldShowRequestPermissionRationale(activity, permissions[index])) {
                                LOG.e("permission", "explain why we need to open the permission");

                                ZMDialog zmDialog = new ZMDialog.Builder(activity)
                                        .setMessage(alertDialogMessages[index])
                                        .setPositiveMessage("开启")
                                        .setPositiveClickEvent(new ZMEventSubscriber() {
                                            @Override
                                            public void onNext(Object o) {
                                                super.onNext(o);
                                                requestOnePermission(activity, permissions[index]);
                                            }
                                        }).show();

                            } else {
                                requestPermissionList.add(permissions[index]);
                            }
                        }
                    }

                    int size = requestPermissionList.size();
                    if (size > 0) {
                        requestGroupPermission(activity, requestPermissionList, requestCode);
                    }

                } else {
                    throw new IllegalArgumentException("the length of Permission Array need to equal of AlertMessage Array's  ");
                }
            } else {
                throw new IllegalArgumentException("Permission Array and AlertMessage Array couldn't be empty");
            }
        }
    }

    /**
     * 开启多个危险权限请求
     *
     * @param fragment
     * @param permissions
     * @param alertDialogMessages
     * @param requestCode
     */
    protected static void takeGroupPermissions(final Fragment fragment, final String[] permissions,
                                               String[] alertDialogMessages, final int requestCode) {
        if (fragment != null && permissions != null && alertDialogMessages != null) {
            int permissionLength = permissions.length;
            int alertMessageLength = alertDialogMessages.length;
            if (permissionLength > 0 && alertMessageLength > 0) {

                //存放需要授权的危险权限
                List<String> requestPermissionList = new ArrayList<>();

                if (permissionLength == alertMessageLength) {
                    int[] permissionFlags = new int[permissionLength];

                    for (int i = 0; i < permissionLength; i++) {
                        final int index = i;
                        permissionFlags[index] = ContextCompat.checkSelfPermission(fragment.getContext(), permissions[index]);

                        if (PackageManager.PERMISSION_DENIED == permissionFlags[index]) {
                            //之前拒绝过,则需要解释
                            if (ActivityCompat.shouldShowRequestPermissionRationale(fragment.getActivity(), permissions[index])) {
                                LOG.e("permission", "explain why we need to open the permission");

                                ZMDialog zmDialog = new ZMDialog.Builder(fragment.getContext())
                                        .setMessage(alertDialogMessages[index])
                                        .setPositiveMessage("开启")
                                        .setPositiveClickEvent(new ZMEventSubscriber() {
                                            @Override
                                            public void onNext(Object o) {
                                                super.onNext(o);
                                                requestOnePermission(fragment.getActivity(), permissions[index]);
                                            }
                                        }).show();

                            } else {
                                requestPermissionList.add(permissions[index]);
                            }
                        }
                    }

                    int size = requestPermissionList.size();
                    if (size > 0) {
                        requestGroupPermission(fragment, requestPermissionList, requestCode);
                    }

                } else {
                    throw new IllegalArgumentException("the length of Permission Array need to equal of AlertMessage Array's  ");
                }
            } else {
                throw new IllegalArgumentException("Permission Array and AlertMessage Array couldn't be empty");
            }
        }
    }

    /**
     * 开启一个危险权限请求
     *
     * @param activity
     * @param permission   危险权限内容
     * @param alertMessage 用户拒绝授权的警告信息
     */
    protected static void takeOnePermission(final Activity activity, final String permission, String alertMessage) {
        if (!TextUtils.isEmpty(permission) && !TextUtils.isEmpty(alertMessage) && activity != null) {
            int selfPermission = ContextCompat.checkSelfPermission(activity, permission);
            //没有授权
            if (PackageManager.PERMISSION_DENIED == selfPermission) {
                //之前拒绝过,则需要解释
                if (ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)) {

                    AlertDialog.Builder builder = new AlertDialog.Builder(activity)
                            .setTitle("提示")
                            .setMessage(alertMessage)
                            .setPositiveButton("开启", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                    requestOnePermission(activity, permission);
                                }
                            });

                    builder.create().show();

                } else {
                    requestOnePermission(activity, permission);
                }
            }
        }
    }

    /**
     * 开启一个危险权限请求
     *
     * @param fragment
     * @param permission   危险权限内容
     * @param alertMessage 用户拒绝授权的警告信息
     */
    protected static void takeOnePermission(final Fragment fragment, final String permission, String alertMessage, final int requestCode) {
        if (!TextUtils.isEmpty(permission) && !TextUtils.isEmpty(alertMessage) && fragment != null) {
            int selfPermission = ContextCompat.checkSelfPermission(fragment.getContext(), permission);
            //没有授权
            if (PackageManager.PERMISSION_DENIED == selfPermission) {
                //之前拒绝过,则需要解释
                if (ActivityCompat.shouldShowRequestPermissionRationale(fragment.getActivity(), permission)) {

                    AlertDialog.Builder builder = new AlertDialog.Builder(fragment.getContext())
                            .setTitle("提示")
                            .setMessage(alertMessage)
                            .setPositiveButton("开启", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                    requestOnePermission(fragment, permission, requestCode);
                                }
                            });

                    builder.create().show();

                } else {
                    requestOnePermission(fragment, permission, requestCode);
                }
            }
        }
    }

    /**
     * 开启一个危险权限请求
     *
     * @param activity
     * @param permission   危险权限内容
     * @param alertMessage 用户拒绝授权的警告信息
     * @param requestCode
     */
    protected static void takeOnePermission(final Activity activity, final String permission, String alertMessage, final int requestCode) {
        if (!TextUtils.isEmpty(permission) && !TextUtils.isEmpty(alertMessage) && activity != null) {
            int selfPermission = ContextCompat.checkSelfPermission(activity, permission);
            //没有授权
            if (PackageManager.PERMISSION_DENIED == selfPermission) {
                //之前拒绝过,则需要解释
                if (ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)) {

                    AlertDialog.Builder builder = new AlertDialog.Builder(activity)
                            .setTitle("提示")
                            .setMessage(alertMessage)
                            .setPositiveButton("开启", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                    requestOnePermission(activity, permission, requestCode);
                                }
                            });

                    builder.create().show();

                } else {
                    requestOnePermission(activity, permission, requestCode);
                }
            }
        }
    }


    //授予权限 低级模块 request系列对take系列模块提供方法支持
    private static void requestOnePermission(Activity activity, String permission) {
        //开启定位权限
        requestOnePermission(activity, permission, REQUEST_CODE_DEFAULT);
    }

    private static void requestOnePermission(Activity activity, String permission, int requestCode) {
        if (activity != null && permission != null) {
            ActivityCompat.requestPermissions(
                    activity,
                    new String[]{permission},
                    requestCode
            );
        }
    }

    private static void requestOnePermission(Fragment fragment, String permission, int requestCode) {
        if (fragment != null && permission != null) {
            fragment.requestPermissions(
                    new String[]{permission},
                    requestCode
            );
        }
    }

    private static void requestGroupPermission(Activity activity, String[] permissions) {
        requestGroupPermission(activity, permissions, REQUEST_CODE_DEFAULT);
    }

    private static void requestGroupPermission(Activity activity, String[] permissions, int requestCode) {
        if (activity != null && permissions != null) {
            if (permissions.length > 0) {
                ActivityCompat.requestPermissions(
                        activity,
                        permissions,
                        requestCode
                );
            }
        }
    }

    private static void requestGroupPermission(Activity activity, List<String> permissionList) {
        requestGroupPermission(activity, permissionList, REQUEST_CODE_DEFAULT);
    }

    private static void requestGroupPermission(Activity activity, List<String> permissionList, int requestCode) {
        if (permissionList != null && activity != null) {
            int size = permissionList.size();
            if (size > 0) {
                String[] permissions = new String[size];
                for (int i = 0; i < size; i++) {
                    permissions[i] = permissionList.get(i);
                }

                ActivityCompat.requestPermissions(
                        activity,
                        permissions,
                        requestCode
                );
            }
        }
    }

    private static void requestGroupPermission(Fragment fragment, List<String> permissionList, int requestCode) {
        if (permissionList != null && fragment != null) {
            int size = permissionList.size();
            if (size > 0) {
                String[] permissions = new String[size];
                for (int i = 0; i < size; i++) {
                    permissions[i] = permissionList.get(i);
                }

                fragment.requestPermissions(
                        permissions,
                        requestCode
                );
            }
        }
    }

}
